<template>
  <div class="image-list clearfix" :class="{ multiple }">
    <!-- 文件列表 -->
    <!-- draggable是拖拽组件 -->
    <draggable
      v-if="selectedItems.length"
      v-model="selectedItems"
      @start="drag = true"
      @end="drag = false"
      @update="onUpdate"
      class="draggable-container"
    >
      <transition-group class="draggable-item" type="transition" :name="'flip-list'">
        <div
          v-for="(item, index) in selectedItems"
          :key="item.file_id"
          class="file-item"
          :style="{ width: `${width}px`, height: `${width}px` }"
        >
          <!-- 预览图 -->
          <a :href="item.preview_url" target="_blank">
            <div class="img-cover" :style="{ backgroundImage: `url('${item.preview_url}')` }"></div>
          </a>
          <!-- 删除文件 -->
          <a-icon class="icon-close" theme="filled" type="close-circle" @click="handleDeleteFileItem(index)" />
        </div>
      </transition-group>
    </draggable>
    <!-- 图片上传器 -->
    <!-- 如果单选, selectedItems无内容时 显示 -->
    <!-- 如果多选, selectedItems数量小于 maxNum 显示 -->
    <div
      v-show="(!multiple && selectedItems.length <= 0) || (multiple && selectedItems.length < maxNum)"
      class="selector"
      :style="{ width: `${width}px`, height: `${width}px` }"
      title="点击上传图片"
    >
      <el-upload
        class="uploader"
        :action="uploadAction"
        :on-success="handleSuccess"
        :headers="headers"
        :show-file-list="false"
        :before-upload="beforeUpload"
        list-type="picture-card"
        :multiple="true"
      >
        <i slot="default" class="el-icon-plus"></i>
      </el-upload>
    </div>
  </div>
</template>

<script>
import PropTypes from 'ant-design-vue/es/_util/vue-types'
import draggable from 'vuedraggable'
import cloneDeep from 'lodash.clonedeep'
import { ACCESS_TOKEN, TENANT_ID, ACCOUNT_BOOK } from '@/store/mutation-types'
import Vue from 'vue'

// 图片上传组件
export default {
  name: 'SelectImage',
  components: {
    draggable,
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    // 多选模式, 如果false为单选
    multiple: PropTypes.bool.def(false),
    // 最大选择的数量限制, multiple模式下有效
    maxNum: PropTypes.integer.def(10),
    // 默认选中的文件
    defaultList: PropTypes.array.def([]),
    // 元素的尺寸(宽)
    width: PropTypes.integer.def(80),
  },
  data() {
    return {
      // 选择的图片列表
      selectedItems: [],
      // 禁止传参 (防止selectedItems为空时defaultList重新赋值)
      allowProps: true,
      // 上传加载状态
      uploading: false,
      // 上传接口地址
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',

      headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
    }
  },
  watch: {
    // 设置默认数据
    defaultList: {
      // 首次加载的时候执行函数
      immediate: true,
      handler(val) {
        const { selectedItems, allowProps } = this
        if (val.length && !selectedItems.length && allowProps) {
          this.selectedItems = cloneDeep(val)
          this.onChange()
        }
      },
    },
  },
  methods: {
    // 拖动排序后的回调事件
    onUpdate() {
      this.onChange()
    },

    // 重置选中的图片
    resetImages() {
      this.selectedItems = []
      this.allowProps = true
      this.onChange()
    },

    // 上传前检查
    beforeUpload(file) {
      // 检查文件类型
      const isImage = file.type.indexOf('image/') === 0
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }

      // 检查文件大小，限制为2MB
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!')
      }

      // 返回false将阻止默认上传行为
      return isImage && isLt2M
    },

    // 处理上传变化
    // handleUploadChange(info) {
    //   if (info.file.status === 'uploading') {
    //     this.uploading = true
    //     return
    //   }

    //   if (info.file.status === 'done') {
    //     this.uploading = false
    //     // 假设上传成功后，服务器返回的数据格式为：{status: 'success', data: {file_id: '1', preview_url: 'url'}}
    //     const response = info.file.response

    //     console.log('response', response)
    //     if (response && response.status === 'success') {
    //       const fileInfo = response.data
    //       // 添加到已选图片中
    //       if (this.multiple) {
    //         this.selectedItems.push(fileInfo)
    //       } else {
    //         this.selectedItems = [fileInfo]
    //       }
    //       this.onChange()
    //     } else {
    //       this.$message.error('上传失败')
    //     }
    //   } else if (info.file.status === 'error') {
    //     this.uploading = false
    //     this.$message.error('上传失败: ' + info.file.error.message)
    //   }
    // },
    handleSuccess(e) {
      if (e.success === true) {
        if (this.multiple) { 
          if (this.selectedItems.length < this.maxNum) {
            // 构造文件信息对象
            const fileInfo = {
              file_id: e.message, // 使用图片路径作为file_id
              preview_url: e.message // 预览URL就是图片路径
            }
            // 根据多选/单选模式添加到已选图片中
            this.selectedItems.push(fileInfo)
            // 触发change事件
            this.onChange()
          } else {
            this.$message.error(`最多只能上传 ${this.maxNum} 张图片!`)
          }
        } else {
          this.selectedItems = [fileInfo]
        }
      } else {
        this.$message.error('图片上传失败')
      }
    },

    // 删除文件
    handleDeleteFileItem(index) {
      this.selectedItems.splice(index, 1)
      if (this.selectedItems.length === 0) {
        this.allowProps = false
      }
      this.onChange()
    },

    // 触发change事件
    onChange() {
      const { multiple, selectedItems } = this
      if (selectedItems.length <= 0) {
        return this.$emit('change', multiple ? '' : 0)
      }
      
      // 获取所有file_id
      const fileIds = selectedItems.map(item => item.file_id)
      
      // 生成结果：多选时返回逗号分隔的字符串，单选时返回单个URL
      const result = multiple ? fileIds.join(',') : selectedItems[0].file_id
      
      // 触发change事件
      return this.$emit('change', result, selectedItems)
    },
  },
}
</script>

<style lang="less" scoped>
/deep/.flip-list-move {
  transition: transform 0.3s !important;
}
/deep/.no-move {
  transition: transform 0s;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  
  // 多选模式下margin
  &.multiple {
    .file-item,
    .selector {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}

.draggable-container {
  display: flex;
  flex-wrap: wrap;
}

// 文件元素
.file-item {
  display: inline-block;
  width: 80px;
  height: 80px;
  position: relative;
  padding: 2px;
  border: 1px solid #ddd;
  background: #fff;
  
  .img-cover {
    display: block;
    width: 100%;
    height: 100%;
    background: no-repeat center center / 100%;
  }
  &:hover {
    .icon-close {
      display: block;
    }
  }
  .icon-close {
    display: none;
    position: absolute;
    top: -8px;
    right: -8px;
    cursor: pointer;
    font-size: 16px;
    color: #c5c5c5;
    &:hover {
      color: #7d7d7d;
    }
  }
  &:hover {
    border: 1px solid #a7c3de;
  }
}

// 选择器
.selector {
  display: inline-block;
  width: 80px;
  height: 80px;
  border: 1px dashed #e2e2e2;
  text-align: center;
  color: #dad9d9;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  &:hover {
    border: 1px dashed #40a9ff;
    color: #40a9ff;
  }

  ::v-deep .el-dialog__footer {
    border-top: 1px solid #e3e3e3;
  }
  ::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
